import { store } from '@/store';
import { list } from '@/api/render/index';

export const renderStore = defineStore('render', () => {
  const cacheData = {};
  const cacheDataRender = {};

  /**
   * 渲染数据
   * 该方法不请求数据，如果需要加载数据请提前使用 loadData加载好数据
   * @param {*} renderCode 渲染来源
   * @param {*} keyField key字段名
   * @param {*} valueField value字段名
   * @param {*} value 要渲染的值
   * @returns 渲染后的值
   */
  const render = function (renderCode, keyField, valueField, value) {
    let data = getRenderJson(renderCode, keyField, valueField);
    if (!data) {
      return null;
    }
    return data[value];
  };

  /**
   *  将数据转换为渲染的json
   * 该方法不请求数据，如果需要加载数据请提前使用 loadData加载好数据
   * @param {*} renderCode 渲染来源
   * @param {*} keyField  key字段名
   * @param {*} valueField value字段名
   * @returns  json
   */
  const getRenderJson = function (renderCode, keyField, valueField) {
    let renderKey = `${renderCode}@render@${keyField}@${valueField}`;

    let renderData = cacheDataRender[renderKey];
    if (!renderData) {
      let data = cacheData[renderCode];
      if (!data) {
        return null;
      }

      renderData = {};
      for (let d of data) {
        renderData[d[keyField]] = d[valueField];
      }
      cacheDataRender[renderKey] = renderData;
    }
    return renderData;
  };

  const getCacheData = function (renderCode) {
    return cacheData[renderCode];
  };

  /**
   * 载入渲染数据
   * @renderCodes {*} renderCodes 渲染code的集合
   * resolve调用没有传入参数，如果需要取直播可以通过getCacheData获取加载后的值
   * @returns Promise
   */
  const loadData = function (renderCodes) {
    return new Promise((resolve, reject) => {
      // 先判断缓存里是否有数据，没有才请求后台加载数据
      let loadParams = [];
      for (let key of renderCodes) {
        if (!cacheData[key]) {
          loadParams.push(key);
        }
      }

      if (loadParams.length == 0) {
        resolve();
      } else {
        list({ codes: renderCodes })
          .then(({ data }) => {
            for (const key in data) {
              cacheData[key] = data[key];
            }
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      }
    });
  };

  const clearData = function (removeKey) {
    for (let datakey in cacheData) {
      if (datakey.indexOf(removeKey) >= 0) {
        delete cacheData[datakey];
      }
    }
    for (let datakey in cacheDataRender) {
      if (datakey.indexOf(removeKey) >= 0) {
        delete cacheDataRender[datakey];
      }
    }
  };

  return { render, getRenderJson, loadData, getCacheData, clearData };
});

// 非setup
export function renderStoreHook() {
  return renderStore(store);
}
